<template>
  <d2-container class="page">
    <el-header>
      <el-row>
        <el-col :offset="4" :span="16">
          <div style="text-align: left" class="logo">
            <img src="@/assets/image/dvadmin-black.png" alt="" style="height: 100%;width: 100%;">
          </div>
          <div style="text-align: right">
            <el-button v-if="!token" size="mini" type="success" icon="el-icon-user-solid"
                       @click="$router.push('/login')">
              请登录
            </el-button>
            <el-tag v-if="token" type="success" size="mini">当前租户：{{ clientInfo.name }}</el-tag>
            <el-tag v-if="token" style="margin-left: 10px;" type="info" size="mini">
              当前套餐：{{ clientInfo.package_manage_name }}
            </el-tag>
            <el-tag v-if="token" style="margin-left: 10px;margin-right: 10px;" size="mini">
              有效期：{{ clientInfo.start_datetime }} 至 {{ clientInfo.paid_until }}
            </el-tag>
            <el-button type="primary" size="mini" icon="el-icon-s-promotion" @click="$router.push('/register')">
              免费试用
            </el-button>
            <el-button v-if="token" size="mini" icon="el-icon-s-home" @click="$router.push('/')">返回首页</el-button>
          </div>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <div class="section page-banner">
        <div class="container">
          <div class="row top-body">
            <h3>套餐购买</h3>
            <p style="margin-bottom: 10px;">
              从个人到企业/组织，满足不同规模项目各阶段需求，为你和你的企业/组织创造更多价值</p>
            <p style="color:red;">套餐购买高级版本后无法回退到低级版本!</p>
          </div>
          <div class="middle-body-item middle-body-item-recommend">
            <el-row>
              <el-col :span="(24 / packageInfo.length) > 6 ? (24 / packageInfo.length ) : 6"
                      v-for="(item,index) in packageInfo" :key="index">
                <el-card class="box-card">
                  <div class="t1">
                    <p class="title">{{ item.name }}</p>
                    <p class="subtitle">{{ item.description }}</p>
                    <p class="price" style="height: 100px;">
                    <span v-for="(price,inx) in item.package_price" :key="inx">
                      <span class="price-number">{{ price.price }} </span>元 {{ price.number }} {{ price.time_unit }}
                      <br>
                    </span>
                    <p class="priceinfo">&nbsp;</p>
                    <el-button round size="small"
                               v-if="item.package_price && item.package_price.length === 1 && Number(item.package_price[0].price) === 0"
                               @click="$router.push('/register')">免费试用
                    </el-button>
                    <el-button round size="small" v-else-if="!token" @click="buyClick(index)">
                      {{ item.sort }}-{{ clientInfo.package_manage_sort }}立即购买
                    </el-button>
                    <el-button
                      round
                      size="small"
                      v-else
                      @click="buyClick(index)"
                      :disabled="item.sort < clientInfo.package_manage_sort">
                      {{ item.sort }}-{{ clientInfo.package_manage_sort }}立即购买
                    </el-button>
                  </div>
                  <hr class="line">
                  <table class="table" align="center">
                    <tbody>
                    <tr v-for="(menu,index ) in item.features_menu_name" :key="index">
                      <td class="left">{{ menu.name }}</td>
                      <td class="right">√</td>
                    </tr>
                    </tbody>
                  </table>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
    </el-main>
    <el-dialog
      title="微信支付"
      :visible.sync="wechatPayDialogVisible"
      v-if="wechatPayDialogVisible"
      append-to-body
      destroy-on-close
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="440px">
      <div class="pay-cards-wrap" style="text-align: center">
        <div class="text">
          扫码支付
        </div>
        <div class="qrcode-wrap" style="text-align: center">
          <div class="pay-cards-wrap">
            <div class="qrcode-price">
              <p class="price-p" style="margin-top: 80px;">
                实付:
                <span class="actual-unit">￥</span>
                <span class="actual-price">{{ buyPackage[activeSvipIndex] && buyPackage[activeSvipIndex].price }}</span>
                <span class="pay-icon"></span>
              </p>
            </div>
          </div>
          <div>
            <div id="qrcode">
              <div id="qrCode" ref="qrCodeDiv"></div>
              <div v-if="!isQrCode" style="width: 102px;height: 102px;">
                <div id="pancashier_qrcode_error" @click="wechatPayCodeUrl">
                  重新获取支付码
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="pay-cards-wrap" style="padding-top: 40px;">
        <div class="qrcode-price" style="margin: 0">
          <p class="price-p" style="margin-left: 20px;float: revert;">
            <span>
              预计获得天数：套餐天数<span
              class="actual-price">{{ getTrialCutOffTime(buyPackage[activeSvipIndex]) }}</span>
              <span class="actual-unit">天</span>
            </span>
            <span>
              + 折算原有套餐天数<span class="actual-price">{{
                getTrialCutOffTimeConvert(buyPackage[activeSvipIndex])
              }}</span>
              <span class="actual-unit">天</span>
            </span>
          </p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="wechatPayDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="wechatPayComplete" v-loading="buyLoading">支付完成</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="购买套餐"
      v-if="buyDialogVisible"
      :visible.sync="buyDialogVisible"
      append-to-body
      destroy-on-close
      width="600px">
      <el-row style="text-align: center">
        <el-col :span="(24 / buyPackage.length) > 6 ? (24 / buyPackage.length ) : 6" v-for="(item,index) in buyPackage"
                :key="index">
          <div class="productItem" :class="{activeSvip: activeSvipIndex === index}" @click="activeSvipIndex=index">
            <div class="bubble" style="display: none;"></div>
            <div class="main-content"><!---->
              <div>
                <div class="product-name">
                  {{ item.number }} {{ item.time_unit }}
                </div>
                <div class="cost-info">
                  <span class="rmb">￥</span>
                  <span class="price">{{ item.price }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <div class="pay-cards-wrap">
          <div class="qrcode-price">
            <p class="price-p">
              实付:
              <span class="actual-unit">￥</span>
              <span class="actual-price">{{ buyPackage[activeSvipIndex] && buyPackage[activeSvipIndex].price }}</span>
              <span class="pay-icon"></span>
            </p>
            <p class="price-p" style="margin-left: 20px;float: revert;">
              <span>
                预计获得天数：套餐天数<span
                class="actual-price">{{ getTrialCutOffTime(buyPackage[activeSvipIndex]) }}</span>
                <span class="actual-unit">天</span>
              </span>
              <span>
                + 折算原有套餐天数<span class="actual-price">{{
                  getTrialCutOffTimeConvert(buyPackage[activeSvipIndex])
                }}</span>
                <span class="actual-unit">天</span>
              </span>
            </p>
          </div>
        </div>
        <el-button @click="buyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="wechatPayClick">支 付</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import * as api from './api'
import XEUtils from 'xe-utils'
import util from '@/libs/util'
import QRCode from 'qrcodejs2'
import { getClientOpeningRecordData } from '../myClientInfo/api'

export default {
  name: 'myClientInfo',
  data () {
    return {
      loginUrl: 'http://public.kfm168.com:8080/',
      menuData: [],
      menuCheckedKeys: [],
      data: [],
      clientInfo: {},
      packageInfo: [],
      buyDialogVisible: false,
      wechatPayDialogVisible: false,
      buyIndex: 0,
      buyPackage: [],
      activeSvipIndex: 0,
      isQrCode: false,
      buyLoading: false,
      buySetInterval: null,
      buySelectNumber: 5,
      outTradeNo: null,
      token: util.cookies.get('token'),
      clientOpeningRecordData: []
    }
  },
  created () {
    this.getAllPackageManage()
    // this.initMenu()
    if (this.token) {
      this.getClientInfo()
      this.getClientOpeningRecordData()
    }
  },
  methods: {
    // 获取所有套餐信息
    getAllPackageManage () {
      api.getAllPackageManage().then(ret => {
        this.packageInfo = ret.data
      })
    },
    initMenu () {
      api.getAllMenu().then(ret => {
        const data = ret.data.data || ret.data
        this.menuData = XEUtils.toArrayTree(JSON.parse(JSON.stringify(data)).map(val => {
          val.disabled = true
          return val
        }), { parentKey: 'parent', strict: false })
      })
    },
    // 获取当前用户租户信息
    getClientInfo () {
      api.getClientInfo().then(ret => {
        this.clientInfo = ret.data
      })
    },
    getBaseURL () {
      return `${location.protocol}//${this.clientInfo.domain}${location.port ? ':' : ''}${location.port}/`
    },
    // 一键复制
    doCopy () {
      this.$copyText(this.getBaseURL()).then(() => {
        this.$message.success('已复制')
      })
    },
    // 一键跳转
    openWindow () {
      window.open(this.getBaseURL())
    },
    // 立即购买
    buyClick (index) {
      // 1. 校验是否登录，未登录提示请注册试用
      // 2. 已登录，弹出购买窗口
      const token = util.cookies.get('token')
      if (!token) {
        this.$confirm('您还没有登录, 请登录后继续?', '提示', {
          confirmButtonText: '登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push('/login')
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      } else {
        this.buyIndex = index
        this.buyPackage = this.packageInfo[index].package_price || []
        this.buyDialogVisible = true
      }
    },
    // 获取支付url
    wechatPayCodeUrl () {
      api.wechatPayCodeUrl({
        package_manage_id: this.packageInfo[this.buyIndex].id,
        money: this.buyPackage[this.activeSvipIndex].price
      }).then(res => {
        this.isQrCode = true
        this.outTradeNo = res.data.out_trade_no
        // eslint-disable-next-line no-new
        new QRCode(this.$refs.qrCodeDiv, {
          text: res.data.code_url,
          width: 118,
          height: 118,
          colorDark: '#333333', // 二维码颜色
          colorLight: '#ffffff', // 二维码背景色
          correctLevel: QRCode.CorrectLevel.L// 容错率，L/M/H
        })
      })
    },
    // 支付按钮点击
    wechatPayClick () {
      // 调用支付生成支付二维码
      this.wechatPayDialogVisible = true
      this.wechatPayCodeUrl()
    },
    // 支付完成
    wechatPayComplete () {
      this.wechatPayDialogVisible = true
      this.buyLoading = true
      // 定时去查询支付状态，查询n次
      this.buySetInterval = setInterval(this.buySetIntervalFunction, 2000)
    },
    // 支持状态查询函数
    buySetIntervalFunction () {
      if (this.buySelectNumber <= 0) {
        // 清除并移除定时
        clearInterval(this.buySetInterval)
        this.buySetInterval = null
        this.buyLoading = false
        this.buySelectNumber = 5
        this.$message.error('支付查询失败,请重试!')
        return
      }
      this.buySelectNumber -= 1
      // 调用状态查询接口
      api.wechatPayStatusSelect({
        out_trade_no: this.outTradeNo
      }).then(res => {
        if (res.data.status === 2) {
          // 清除并移除定时
          clearInterval(this.buySetInterval)
          this.buySetInterval = null
          this.buyLoading = false
          this.wechatPayDialogVisible = false
          this.buyDialogVisible = false
          this.$message.success(`成功购买${this.packageInfo[this.buyIndex].name} ${this.buyPackage[this.activeSvipIndex].number} ${this.buyPackage[this.activeSvipIndex].time_unit}`)
          this.getClientInfo()
        }
      })
    },
    // 获取套餐天数
    getTrialCutOffTime (buyPackage) {
      if (!buyPackage) return 0
      // 有效期换算
      let days = Number(buyPackage.number)
      if (buyPackage.time_unit === '年') {
        days = days * 365
      } else if (buyPackage.time_unit === '个月' || buyPackage.time_unit === '月') {
        days = days * 31
      } else if (buyPackage.time_unit === '永久') {
        days = 99999
      }
      return days
    },
    // 获取开通记录
    getClientOpeningRecordData () {
      getClientOpeningRecordData({ status: 2 }).then(res => {
        this.clientOpeningRecordData = res.data
      })
    },
    // 获取折算天数
    getTrialCutOffTimeConvert (buyPackage) {
      // 有效期换算
      const oldData = this.clientOpeningRecordData[0]
      if (!oldData) return 0
      if (!buyPackage) return 0
      // 判断，如果新套餐与旧套餐一样，则天数叠加
      if (oldData.package_manage__sort === this.packageInfo[this.buyIndex].sort) {
        return oldData.trial_cut_off_time + oldData.trial_cut_off_time_convert
      }
      // 日期进行折算
      // 1. 计算之前的套餐剩余天数与对应价格
      var createTimestamp = new Date(oldData.create_datetime)
      createTimestamp.setHours(0, 0, 0, 0)
      // 获取当前日期的时间戳（以毫秒为单位）
      var currentTimestamp = new Date().getTime()
      // 计算时间差（以毫秒为单位）
      var timeDiff = currentTimestamp - createTimestamp.getTime()
      // 将时间差转换为天数（向下取整）
      var daysDiff = oldData.trial_cut_off_time + oldData.trial_cut_off_time_convert - Math.floor(timeDiff / 86400000) + 1
      // 2. 计算当前套餐的价格
      const newDays = this.getTrialCutOffTime(buyPackage)
      const newDailyMoney = parseFloat((buyPackage.price / newDays).toFixed(2))
      const convertDays = parseFloat(((oldData.money / (oldData.trial_cut_off_time + oldData.trial_cut_off_time_convert)) * daysDiff / newDailyMoney).toFixed(0))
      return convertDays < 0 ? 0 : convertDays
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .logo {
  width: 140px;
  height: 50px;
  position: absolute;
  top: 5px;
}

::v-deep .theme-d2 {
  background: #fff !important;
}

::v-deep * {
  vertical-align: middle;
}

::v-deep .top-body {
  p {
    font-size: 14px;
    text-align: center;
    padding-top: 15px;
    margin-bottom: 40px;
  }

  h3 {
    font-size: 28px;
    text-align: center;
    padding-top: 20px;
  }
}

::v-deep .section.page-banner {
  margin-top: 2px;
  padding-top: 30px;
  padding-bottom: 30px;
  background-size: cover;
  background-color: #fff;
}

::v-deep .container {
  width: 970px;
  max-width: none !important;
}

::v-deep .el-header {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25);
  background: #fff;
  color: #333;
  text-align: center;
  line-height: 60px;
}

::v-deep .el-main {
  color: #333;
  text-align: center;
  margin: 0;
  padding: 0;

  .t1 {
    padding-bottom: 20px;
  }

  .title {
    font-size: 22px;
    padding-top: 50px;
    font-weight: bold;
    min-height: 110px;
    padding-left: 20px;
    padding-right: 20px;
  }

  .subtitle {
    font-size: 12px;
    padding-top: 6px;
    min-height: 50px;
    padding-left: 20px;
    padding-right: 20px;
  }

  .price {
    font-size: 14px;
    padding-top: 6px;
  }

  .price .price-number {
    font-weight: bold;
    font-size: 20px;
    padding-right: 5px;
    color: #ff0000;
  }

  .priceinfo {
    padding: 0 0 9px;
  }

  hr {
    margin-top: 18px;
    margin-bottom: 18px;
    border: 0;
    border-top: 1px solid #eeeeee;
    box-sizing: content-box;
    height: 0;
  }
}

::v-deep .middle-body-item {
  .el-col {
    padding: 0 10px;
  }
}

::v-deep .el-card__body, .el-main {
  padding: 0;
}

::v-deep .middle-body-item-recommend .t1 {
  background-image: -webkit-linear-gradient(20deg, #298df8 4%, #1c4de3 100%);
  background-image: -moz-linear-gradient(20deg, #298df8 4%, #1c4de3 100%);
  background-image: -o-linear-gradient(20deg, #298df8 4%, #1c4de3 100%);
  background-image: -ms-linear-gradient(20deg, #298df8 4%, #1c4de3 100%);
  background-image: linear-gradient(70deg, #298df8 4%, #1c4de3 100%);
  -webkit-box-shadow: 0 5px 20px 0 rgba(43, 41, 41, 0.15);
  box-shadow: 0 5px 20px 0 rgba(43, 41, 41, 0.15);
  border-radius: 4px;
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
  color: white;
}

::v-deep body {
  padding-top: 60px;
  font-size: 14px;
  background: #f4f6f8;
  height: 100%;
  line-height: 1.5715;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
  -moz-osx-font-smoothing: grayscale;
  font-feature-settings: 'liga';
  -webkit-text-size-adjust: 100%;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Ubuntu, Helvetica Neue, Helvetica, Arial, PingFang SC, Hiragino Sans GB, Microsoft YaHei UI, Microsoft YaHei, Source Han Sans CN, sans-serif;
  font-weight: 400;
  color: #616161;
}

.table {
  width: 90%;
  max-width: 100%;
  margin-bottom: 18px;
  background-color: transparent;
  border-collapse: collapse;
  border-spacing: 0;
  font-weight: 400;
  color: #616161;
  font-size: 14px;
  line-height: 1.5715;
  -webkit-font-smoothing: antialiased;
  font-feature-settings: 'liga';
  -webkit-text-size-adjust: 100%;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Ubuntu, Helvetica Neue, Helvetica, Arial, PingFang SC, Hiragino Sans GB, Microsoft YaHei UI, Microsoft YaHei, Source Han Sans CN, sans-serif;
  text-rendering: optimizeLegibility;

  .left {
    text-align: left;
  }

  td, th {
    padding: 0;
  }

  td {
    padding: 8px;
    line-height: 1.42857143;
    vertical-align: top;
    border-top: 1px solid #ddd;
  }

  .right {
    text-align: right;
    font-family: 'Source Sans Pro', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  }
}

.productItem {
  padding-top: 30px;
  border: 1px solid #ddd;
  position: relative;
  box-sizing: border-box;
  width: 120px;
  height: 116px;
  display: inline-block;
  margin-right: 12px;
  background-color: #f7f9fc;
  border-radius: 9px;
  cursor: pointer;
  text-align: center;
  -webkit-user-select: none;
  user-select: none;

  .main-content {
    .cost-info {
      width: 100%;
      color: #f60;

      .product-name {
        margin-left: 10px;
        width: 100%;
        height: 16px;
        text-align: center;
        line-height: 16px;
        color: #495366;
        font-size: 16px;
        font-weight: 500;
        margin-top: 16px;
        margin-bottom: 10px;
      }

      .rmb {
        line-height: 20px;
        font-size: 16px;
        vertical-align: baseline;
      }

      .price {
        font-family: DIN Alternate;
        font-size: 30px;
        vertical-align: baseline;
      }
    }
  }
}

.activeSvip {
  background: linear-gradient(101.37deg, #fff9c6 1.05%, #ffe1c2 97.37%);
  border: 2px solid #ffb66d;
  border-radius: 9px;

  .product-name {
    color: #6b2d00;
    font-weight: 700;
  }
}

::v-deep .pay-cards-wrap {
  background: #fff;
  border-radius: 6px;
  margin-right: 20px;

  .text {
    color: #030b1a;
    font-weight: 600;
    font-size: 14px;
    margin-bottom: 10px;
    margin-right: 8px;
    margin-left: 30px;
  }

  .qrcode-wrap {
    position: relative;
    width: 100%;
    box-sizing: border-box;
    zoom: 1;
    overflow: hidden;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;

    #qrcode {
      width: 118px;
      height: 118px;
      padding: 8px;
      box-sizing: border-box;
      background-color: #f7f9fc;
      border-radius: 8px;
    }

  }

  .qrcode-price {
    margin: -6px 0 0 30px;
    top: 50%;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
    font-size: 12px;
    color: #03081a;

    .price-p {
      float: left;
      font-weight: 700;
      margin-bottom: 6px;
      margin-top: 6px;
      font-size: 12px;
      color: #495366;

      .actual-unit {
        margin-left: 2px;
        font-size: 16px;
        font-weight: 700;
        color: #f60;
        vertical-align: baseline;
      }

      .actual-price {
        font-size: 26px;
        color: #f60;
        font-family: DIN Alternate;
        vertical-align: baseline;
      }
    }

    .fixed-width {
      width: 133px;
    }

    .enlarge-gap {
      margin-top: 4px;
      margin-left: 20px;
    }
  }

  #pancashier_qrcode_error {
    cursor: pointer;
    width: 102px;
    height: 102px;
    background: url(https://staticiot.cdn.bcebos.com/pay/static/ic_refresh_2x.png) center 31px / 20px 18px no-repeat rgba(0, 0, 0, 0.9);
    color: rgb(255, 255, 255);
    font-size: 12px;
    text-align: center;
    line-height: 122px;
    user-select: none;
    margin-left: 0px;
    position: absolute;
    z-index: 9;
  }
}
</style>
